<template>
  <div class="code-preview">
    <div class="preview-header">
      <el-tabs v-model="activeTab" @tab-click="handleTabClick">
        <el-tab-pane label="WXML" name="wxml">
          <template slot="label">
            <i class="el-icon-document"></i> WXML
          </template>
        </el-tab-pane>
        <el-tab-pane label="WXSS" name="wxss">
          <template slot="label">
            <i class="el-icon-view"></i> WXSS
          </template>
        </el-tab-pane>
        <el-tab-pane label="JS" name="js">
          <template slot="label">
            <i class="el-icon-cpu"></i> JS
          </template>
        </el-tab-pane>
        <el-tab-pane label="JSON" name="json">
          <template slot="label">
            <i class="el-icon-setting"></i> JSON
          </template>
        </el-tab-pane>
      </el-tabs>
      
      <div class="preview-actions">
        <el-button @click="generateCode" icon="el-icon-refresh">
          重新生成
        </el-button>
        <el-button type="primary" @click="downloadCode" icon="el-icon-download">
          下载代码
        </el-button>
      </div>
    </div>

    <div class="code-content">
      <!-- WXML代码 -->
      <div v-show="activeTab === 'wxml'" class="code-section">
        <div class="code-header">
          <span class="file-name">index.wxml</span>
          <el-button size="mini" @click="copyCode('wxml')">复制</el-button>
        </div>
        <pre><code class="language-xml">{{ wxmlCode }}</code></pre>
      </div>

      <!-- WXSS代码 -->
      <div v-show="activeTab === 'wxss'" class="code-section">
        <div class="code-header">
          <span class="file-name">index.wxss</span>
          <el-button size="mini" @click="copyCode('wxss')">复制</el-button>
        </div>
        <pre><code class="language-css">{{ wxssCode }}</code></pre>
      </div>

      <!-- JS代码 -->
      <div v-show="activeTab === 'js'" class="code-section">
        <div class="code-header">
          <span class="file-name">index.js</span>
          <el-button size="mini" @click="copyCode('js')">复制</el-button>
        </div>
        <pre><code class="language-javascript">{{ jsCode }}</code></pre>
      </div>

      <!-- JSON代码 -->
      <div v-show="activeTab === 'json'" class="code-section">
        <div class="code-header">
          <span class="file-name">index.json</span>
          <el-button size="mini" @click="copyCode('json')">复制</el-button>
        </div>
        <pre><code class="language-json">{{ jsonCode }}</code></pre>
      </div>
    </div>
  </div>
</template>

<script>
import JSZip from 'jszip'

export default {
  name: 'CodePreview',
  props: {
    pageData: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      activeTab: 'wxml',
      wxmlCode: '',
      wxssCode: '',
      jsCode: '',
      jsonCode: ''
    }
  },
  watch: {
    pageData: {
      handler() {
        this.generateCode()
      },
      immediate: true,
      deep: true
    }
  },
  methods: {
    // 生成小程序代码
    generateCode() {
      this.generateWXML()
      this.generateWXSS()
      this.generateJS()
      this.generateJSON()
    },

    // 生成WXML代码
    generateWXML() {
      let wxml = `<!--index.wxml-->\n<view class="container">\n`
      
      // 添加顶部状态栏
      wxml += `  <!-- 状态栏 -->\n`
      wxml += `  <view class="status-bar"></view>\n\n`
      
      this.pageData.components.forEach(component => {
        wxml += this.generateComponentWXML(component)
      })
      
      wxml += `</view>`
      this.wxmlCode = wxml
    },

    // 生成组件WXML
    generateComponentWXML(component) {
      const { type, data, style } = component
      let wxml = ''
      
      switch (type) {
        case 'campus':
          wxml += `  <!-- 校区名称 -->\n`
          wxml += `  <view class="campus-header">\n`
          wxml += `    <text class="campus-name">{{campusName}}</text>\n`
          wxml += `  </view>\n\n`
          break
          
        case 'search':
          wxml += `  <!-- 搜索框 -->\n`
          wxml += `  <view class="search-container">\n`
          wxml += `    <view class="search-box">\n`
          wxml += `      <icon class="search-icon" type="search" size="16"></icon>\n`
          wxml += `      <input class="search-input" placeholder="${data.placeholder}" />\n`
          wxml += `    </view>\n`
          wxml += `  </view>\n\n`
          break
          
        case 'banner':
          wxml += `  <!-- 轮播图 -->\n`
          wxml += `  <view class="banner-container">\n`
          wxml += `    <swiper class="banner-swiper" indicator-dots="{{true}}" autoplay="{{${data.autoPlay}}}" interval="{{${data.interval}}}">\n`
          wxml += `      <swiper-item wx:for="{{bannerList}}" wx:key="id">\n`
          wxml += `        <image class="banner-image" src="{{item.image}}" mode="aspectFill" bindtap="onBannerTap" data-link="{{item.link}}"></image>\n`
          wxml += `      </swiper-item>\n`
          wxml += `    </swiper>\n`
          wxml += `  </view>\n\n`
          break
          
        case 'goods':
          wxml += `  <!-- 商品展示 -->\n`
          wxml += `  <view class="goods-container">\n`
          wxml += `    <view class="goods-grid">\n`
          wxml += `      <view class="goods-item" wx:for="{{goodsList}}" wx:key="id" bindtap="onGoodsTap" data-id="{{item.id}}">\n`
          wxml += `        <image class="goods-image" src="{{item.image}}" mode="aspectFill"></image>\n`
          wxml += `        <view class="goods-info">\n`
          wxml += `          <text class="goods-name">{{item.name}}</text>\n`
          wxml += `          <text class="goods-price">¥{{item.price}}</text>\n`
          wxml += `        </view>\n`
          wxml += `      </view>\n`
          wxml += `    </view>\n`
          wxml += `  </view>\n\n`
          break

        case 'distribution-goods':
          wxml += `  <!-- 分销商品 -->\n`
          wxml += `  <view class="distribution-goods-container">\n`
          wxml += `    <view class="distribution-goods-grid">\n`
          wxml += `      <view class="distribution-goods-item" wx:for="{{distributionGoodsList}}" wx:key="goodId" bindtap="onDistributionGoodsTap" data-id="{{item.goodId}}">\n`
          wxml += `        <image class="distribution-goods-image" src="{{item.goodPicture}}" mode="aspectFill"></image>\n`
          wxml += `        <view class="distribution-goods-info">\n`
          wxml += `          <text class="goods-name">{{item.goodName}}</text>\n`
          wxml += `          <text class="goods-price">¥{{item.goodPrice}}</text>\n`
          wxml += `        </view>\n`
          wxml += `      </view>\n`
          wxml += `    </view>\n`
          wxml += `  </view>\n\n`
          break
          
        case 'quick':
          wxml += `  <!-- 快捷入口 -->\n`
          wxml += `  <view class="quick-container">\n`
          wxml += `    <view class="quick-grid">\n`
          wxml += `      <view class="quick-item" wx:for="{{quickEntries}}" wx:key="id" bindtap="onQuickTap" data-link="{{item.link}}">\n`
          wxml += `        <text class="quick-name">{{item.name}}</text>\n`
          wxml += `      </view>\n`
          wxml += `    </view>\n`
          wxml += `  </view>\n\n`
          break

        case 'entries':
          wxml += `  <!-- 功能入口 -->\n`
          wxml += `  <view class="entries-container">\n`
          wxml += `    <view class="entries-grid">\n`
          wxml += `      <view class="entry-item" wx:for="{{entriesList}}" wx:key="id" bindtap="onEntryTap" data-link="{{item.link}}">\n`
          wxml += `        <view class="entry-icon">\n`
          wxml += `          <image wx:if="{{item.builtInIcon}}" class="icon-image" src="{{item.builtInIcon}}" mode="aspectFill"></image>\n`
          wxml += `          <text wx:if="{{!item.builtInIcon}}" class="icon-default">📱</text>\n`
          wxml += `        </view>\n`
          wxml += `        <text class="entry-name">{{item.name}}</text>\n`
          wxml += `      </view>\n`
          wxml += `    </view>\n`
          wxml += `  </view>\n\n`
          break

        case 'notice':
          wxml += `  <!-- 校区公告 -->\n`
          wxml += `  <view class="notice-container">\n`
          wxml += `    <view class="notice-header">\n`
          wxml += `      <text class="notice-title">校区公告</text>\n`
          wxml += `    </view>\n`
          wxml += `    <view class="notice-list">\n`
          wxml += `      <view class="notice-item" wx:for="{{noticeList}}" wx:key="id" bindtap="onNoticeTap" data-id="{{item.id}}">\n`
          wxml += `        <text class="notice-text">{{item.title}}</text>\n`
          wxml += `        <text class="notice-time" wx:if="{{${data.showTime}}}">{{item.publishTime}}</text>\n`
          wxml += `      </view>\n`
          wxml += `    </view>\n`
          wxml += `  </view>\n\n`
          break

        case 'recommend':
          wxml += `  <!-- 品牌推荐 -->\n`
          wxml += `  <view class="recommend-container">\n`
          wxml += `    <view class="recommend-header">\n`
          wxml += `      <text class="recommend-title">品牌推荐</text>\n`
          wxml += `    </view>\n`
          wxml += `    <scroll-view class="recommend-scroll" scroll-x="true">\n`
          wxml += `      <view class="recommend-list">\n`
          wxml += `        <view class="recommend-item" wx:for="{{recommendList}}" wx:key="id" bindtap="onRecommendTap" data-link="{{item.link}}">\n`
          wxml += `          <image class="recommend-logo" src="{{item.logo}}" mode="aspectFill" wx:if="{{${data.showLogo}}}"></image>\n`
          wxml += `          <text class="recommend-name">{{item.name}}</text>\n`
          wxml += `        </view>\n`
          wxml += `      </view>\n`
          wxml += `    </scroll-view>\n`
          wxml += `  </view>\n\n`
          break

        case 'image':
          wxml += `  <!-- 图片 -->\n`
          wxml += `  <view class="image-container">\n`
          wxml += `    <image class="custom-image" src="${data.src}" mode="${data.objectFit}" alt="${data.alt}"`
          if (data.clickable && data.link) {
            wxml += ` bindtap="onImageTap" data-link="${data.link}"`
          }
          wxml += `></image>\n`
          wxml += `  </view>\n\n`
          break

        case 'video':
          wxml += `  <!-- 视频 -->\n`
          wxml += `  <view class="video-container">\n`
          wxml += `    <video class="custom-video" src="${data.src}" poster="${data.poster}"`
          wxml += ` autoplay="{{${data.autoplay}}}" loop="{{${data.loop}}}" muted="{{${data.muted}}}" controls="{{${data.controls}}}"`
          wxml += `></video>\n`
          wxml += `  </view>\n\n`
          break

        case 'text':
          wxml += `  <!-- 文本 -->\n`
          wxml += `  <view class="text-container">\n`
          wxml += `    <text class="custom-text">${data.content}</text>\n`
          wxml += `  </view>\n\n`
          break
      }
      
      return wxml
    },

    // 生成WXSS代码
    generateWXSS() {
      let wxss = `/* index.wxss */\n.container {\n  background-color: ${this.pageData.config.backgroundColor || '#f5f5f5'};\n  min-height: 100vh;\n}\n\n`
      
      // 状态栏样式
      wxss += `.status-bar {\n  height: var(--status-bar-height);\n}\n\n`
      
      // 为每个组件生成样式
      this.pageData.components.forEach(component => {
        wxss += this.generateComponentWXSS(component)
      })
      
      this.wxssCode = wxss
    },

    // 生成组件WXSS
    generateComponentWXSS(component) {
      const { type, style } = component
      let wxss = ''
      
      switch (type) {
        case 'campus':
          wxss += `/* 校区名称样式 */\n`
          wxss += `.campus-header {\n`
          wxss += `  padding: ${style.margin || 10}px 20px;\n`
          wxss += `  background-color: ${style.backgroundColor || 'transparent'};\n`
          wxss += `}\n\n`
          wxss += `.campus-name {\n`
          wxss += `  font-size: ${style.fontSize || 18}px;\n`
          wxss += `  color: ${style.color || '#333'};\n`
          wxss += `  font-weight: bold;\n`
          wxss += `}\n\n`
          break
          
        case 'search':
          wxss += `/* 搜索框样式 */\n`
          wxss += `.search-container {\n`
          wxss += `  padding: 15px 20px;\n`
          wxss += `}\n\n`
          wxss += `.search-box {\n`
          wxss += `  display: flex;\n`
          wxss += `  align-items: center;\n`
          wxss += `  background-color: ${style.backgroundColor || '#f0f0f0'};\n`
          wxss += `  border-radius: ${style.borderRadius || 20}px;\n`
          wxss += `  padding: ${style.padding || 10}px 15px;\n`
          wxss += `}\n\n`
          wxss += `.search-icon {\n`
          wxss += `  margin-right: 10px;\n`
          wxss += `  color: #999;\n`
          wxss += `}\n\n`
          wxss += `.search-input {\n`
          wxss += `  flex: 1;\n`
          wxss += `  font-size: 14px;\n`
          wxss += `}\n\n`
          break
          
        case 'banner':
          wxss += `/* 轮播图样式 */\n`
          wxss += `.banner-container {\n`
          wxss += `  margin: ${style.margin || 15}px 20px;\n`
          wxss += `}\n\n`
          wxss += `.banner-swiper {\n`
          wxss += `  height: ${style.height || 160}px;\n`
          wxss += `  border-radius: ${style.borderRadius || 8}px;\n`
          wxss += `  overflow: hidden;\n`
          wxss += `}\n\n`
          wxss += `.banner-image {\n`
          wxss += `  width: 100%;\n`
          wxss += `  height: 100%;\n`
          wxss += `}\n\n`
          break
          
        case 'goods':
          const goodsComponent = this.pageData.components.find(c => c.type === 'goods')
          const goodsColumns = goodsComponent?.data?.columns || 2
          wxss += `/* 商品展示样式 */\n`
          wxss += `.goods-container {\n`
          wxss += `  padding: ${style.padding || 15}px 20px;\n`
          wxss += `  background-color: ${style.backgroundColor || '#fff'};\n`
          wxss += `  border-radius: ${style.borderRadius || 8}px;\n`
          wxss += `  margin: 15px 20px;\n`
          wxss += `}\n\n`
          wxss += `.goods-grid {\n`
          wxss += `  display: grid;\n`
          wxss += `  grid-template-columns: repeat(${goodsColumns}, 1fr);\n`
          wxss += `  gap: 15px;\n`
          wxss += `}\n\n`
          wxss += `.goods-item {\n`
          wxss += `  background: #fff;\n`
          wxss += `  border-radius: 8px;\n`
          wxss += `  overflow: hidden;\n`
          wxss += `  box-shadow: 0 2px 8px rgba(0,0,0,0.1);\n`
          wxss += `}\n\n`
          wxss += `.goods-image {\n`
          wxss += `  width: 100%;\n`
          wxss += `  height: 120px;\n`
          wxss += `}\n\n`
          wxss += `.goods-info {\n`
          wxss += `  padding: 10px;\n`
          wxss += `}\n\n`
          wxss += `.goods-name {\n`
          wxss += `  display: block;\n`
          wxss += `  font-size: 14px;\n`
          wxss += `  color: #333;\n`
          wxss += `  margin-bottom: 8px;\n`
          wxss += `}\n\n`
          wxss += `.goods-price {\n`
          wxss += `  font-size: 16px;\n`
          wxss += `  color: #ff4757;\n`
          wxss += `  font-weight: bold;\n`
          wxss += `}\n\n`
          break

        case 'distribution-goods':
          const distributionComponent = this.pageData.components.find(c => c.type === 'distribution-goods')
          const distributionColumns = distributionComponent?.data?.columns || 2
          wxss += `/* 分销商品样式 */\n`
          wxss += `.distribution-goods-container {\n`
          wxss += `  padding: ${style.padding || 15}px 20px;\n`
          wxss += `  background-color: ${style.backgroundColor || '#fff'};\n`
          wxss += `  border-radius: ${style.borderRadius || 8}px;\n`
          wxss += `  margin: 15px 20px;\n`
          wxss += `}\n\n`
          wxss += `.distribution-goods-grid {\n`
          wxss += `  display: grid;\n`
          wxss += `  grid-template-columns: repeat(${distributionColumns}, 1fr);\n`
          wxss += `  gap: 15px;\n`
          wxss += `}\n\n`
          wxss += `.distribution-goods-item {\n`
          wxss += `  background: #fff;\n`
          wxss += `  border-radius: 8px;\n`
          wxss += `  overflow: hidden;\n`
          wxss += `  box-shadow: 0 2px 8px rgba(0,0,0,0.1);\n`
          wxss += `  border: 1px solid #e3f2fd;\n`
          wxss += `}\n\n`
          wxss += `.distribution-goods-image {\n`
          wxss += `  width: 100%;\n`
          wxss += `  height: 120px;\n`
          wxss += `}\n\n`
          wxss += `.distribution-goods-info {\n`
          wxss += `  padding: 10px;\n`
          wxss += `}\n\n`
          wxss += `.distribution-goods-info .goods-name {\n`
          wxss += `  display: block;\n`
          wxss += `  font-size: 14px;\n`
          wxss += `  color: #333;\n`
          wxss += `  margin-bottom: 8px;\n`
          wxss += `  font-weight: 500;\n`
          wxss += `}\n\n`
          wxss += `.distribution-goods-info .goods-price {\n`
          wxss += `  font-size: 16px;\n`
          wxss += `  color: #ff4757;\n`
          wxss += `  font-weight: bold;\n`
          wxss += `}\n\n`
          break

        case 'quick':
          wxss += `/* 快捷入口样式 */\n`
          wxss += `.quick-container {\n`
          wxss += `  padding: ${style.padding || 15}px 20px;\n`
          wxss += `  background-color: ${style.backgroundColor || '#fff'};\n`
          wxss += `  border-radius: ${style.borderRadius || 8}px;\n`
          wxss += `  margin: 15px 20px;\n`
          wxss += `}\n\n`
          wxss += `.quick-grid {\n`
          wxss += `  display: flex;\n`
          wxss += `  justify-content: space-between;\n`
          wxss += `  flex-wrap: wrap;\n`
          wxss += `}\n\n`
          wxss += `.quick-item {\n`
          wxss += `  padding: 10px;\n`
          wxss += `  text-align: center;\n`
          wxss += `}\n\n`
          wxss += `.quick-name {\n`
          wxss += `  font-size: ${style.fontSize || 12}px;\n`
          wxss += `  color: ${style.color || '#666'};\n`
          wxss += `}\n\n`
          break

        case 'entries':
          const entriesComponent = this.pageData.components.find(c => c.type === 'entries')
          const entriesColumns = entriesComponent?.data?.columns || 4
          wxss += `/* 功能入口样式 */\n`
          wxss += `.entries-container {\n`
          wxss += `  padding: ${style.padding || 15}px 20px;\n`
          wxss += `  background-color: ${style.backgroundColor || '#fff'};\n`
          wxss += `  border-radius: ${style.borderRadius || 8}px;\n`
          wxss += `  margin: 15px 20px;\n`
          wxss += `}\n\n`
          wxss += `.entries-grid {\n`
          wxss += `  display: grid;\n`
          wxss += `  grid-template-columns: repeat(${entriesColumns}, 1fr);\n`
          wxss += `  gap: 15px;\n`
          wxss += `}\n\n`
          wxss += `.entry-item {\n`
          wxss += `  text-align: center;\n`
          wxss += `  padding: 10px;\n`
          wxss += `}\n\n`
          wxss += `.entry-icon {\n`
          wxss += `  width: 40px;\n`
          wxss += `  height: 40px;\n`
          wxss += `  margin-bottom: 8px;\n`
          wxss += `  display: flex;\n`
          wxss += `  align-items: center;\n`
          wxss += `  justify-content: center;\n`
          wxss += `}\n\n`
          wxss += `.icon-image {\n`
          wxss += `  width: 32px;\n`
          wxss += `  height: 32px;\n`
          wxss += `  border-radius: 4px;\n`
          wxss += `}\n\n`
          wxss += `.icon-default {\n`
          wxss += `  font-size: 24px;\n`
          wxss += `  color: #999;\n`
          wxss += `}\n\n`
          wxss += `.entry-name {\n`
          wxss += `  display: block;\n`
          wxss += `  font-size: ${style.fontSize || 14}px;\n`
          wxss += `  color: ${style.color || '#333'};\n`
          wxss += `}\n\n`
          break

        case 'notice':
          wxss += `/* 校区公告样式 */\n`
          wxss += `.notice-container {\n`
          wxss += `  padding: ${style.padding || 15}px 20px;\n`
          wxss += `  background-color: ${style.backgroundColor || '#fff3cd'};\n`
          wxss += `  border-radius: ${style.borderRadius || 8}px;\n`
          wxss += `  margin: 15px 20px;\n`
          wxss += `}\n\n`
          wxss += `.notice-header {\n`
          wxss += `  margin-bottom: 10px;\n`
          wxss += `}\n\n`
          wxss += `.notice-title {\n`
          wxss += `  font-size: 16px;\n`
          wxss += `  font-weight: bold;\n`
          wxss += `  color: ${style.color || '#856404'};\n`
          wxss += `}\n\n`
          wxss += `.notice-item {\n`
          wxss += `  padding: 8px 0;\n`
          wxss += `  border-bottom: 1px solid rgba(0,0,0,0.1);\n`
          wxss += `}\n\n`
          wxss += `.notice-text {\n`
          wxss += `  display: block;\n`
          wxss += `  font-size: ${style.fontSize || 14}px;\n`
          wxss += `  color: ${style.color || '#856404'};\n`
          wxss += `  margin-bottom: 4px;\n`
          wxss += `}\n\n`
          wxss += `.notice-time {\n`
          wxss += `  font-size: 12px;\n`
          wxss += `  color: #999;\n`
          wxss += `}\n\n`
          break

        case 'recommend':
          wxss += `/* 品牌推荐样式 */\n`
          wxss += `.recommend-container {\n`
          wxss += `  padding: ${style.padding || 15}px 20px;\n`
          wxss += `  background-color: ${style.backgroundColor || '#fff'};\n`
          wxss += `  border-radius: ${style.borderRadius || 8}px;\n`
          wxss += `  margin: 15px 20px;\n`
          wxss += `}\n\n`
          wxss += `.recommend-header {\n`
          wxss += `  margin-bottom: 15px;\n`
          wxss += `}\n\n`
          wxss += `.recommend-title {\n`
          wxss += `  font-size: 16px;\n`
          wxss += `  font-weight: bold;\n`
          wxss += `  color: ${style.color || '#333'};\n`
          wxss += `}\n\n`
          wxss += `.recommend-scroll {\n`
          wxss += `  white-space: nowrap;\n`
          wxss += `}\n\n`
          wxss += `.recommend-list {\n`
          wxss += `  display: inline-flex;\n`
          wxss += `  gap: 15px;\n`
          wxss += `}\n\n`
          wxss += `.recommend-item {\n`
          wxss += `  text-align: center;\n`
          wxss += `  min-width: 80px;\n`
          wxss += `}\n\n`
          wxss += `.recommend-logo {\n`
          wxss += `  width: 50px;\n`
          wxss += `  height: 50px;\n`
          wxss += `  border-radius: 8px;\n`
          wxss += `  margin-bottom: 8px;\n`
          wxss += `}\n\n`
          wxss += `.recommend-name {\n`
          wxss += `  display: block;\n`
          wxss += `  font-size: ${style.fontSize || 14}px;\n`
          wxss += `  color: ${style.color || '#333'};\n`
          wxss += `}\n\n`
          break

        case 'image':
          wxss += `/* 图片样式 */\n`
          wxss += `.image-container {\n`
          wxss += `  margin: ${style.margin || 15}px 20px;\n`
          wxss += `  border-radius: ${style.borderRadius || 8}px;\n`
          wxss += `  overflow: hidden;\n`
          wxss += `}\n\n`
          wxss += `.custom-image {\n`
          wxss += `  width: ${component.data.width || 100}%;\n`
          wxss += `  height: ${component.data.height || 100}px;\n`
          wxss += `  border-radius: ${style.borderRadius || 8}px;\n`
          wxss += `}\n\n`
          break

        case 'video':
          wxss += `/* 视频样式 */\n`
          wxss += `.video-container {\n`
          wxss += `  margin: ${style.margin || 15}px 20px;\n`
          wxss += `  border-radius: ${style.borderRadius || 8}px;\n`
          wxss += `  overflow: hidden;\n`
          wxss += `}\n\n`
          wxss += `.custom-video {\n`
          wxss += `  width: ${component.data.width || 100}%;\n`
          wxss += `  height: ${component.data.height || 200}px;\n`
          wxss += `  border-radius: ${style.borderRadius || 8}px;\n`
          wxss += `}\n\n`
          break

        case 'text':
          wxss += `/* 文本样式 */\n`
          wxss += `.text-container {\n`
          wxss += `  padding: ${style.padding || 8}px 20px;\n`
          wxss += `  margin: ${style.margin || 10}px 0;\n`
          wxss += `}\n\n`
          wxss += `.custom-text {\n`
          wxss += `  font-size: ${style.fontSize || 14}px;\n`
          wxss += `  color: ${style.color || '#666'};\n`
          wxss += `  text-align: ${style.textAlign || 'left'};\n`
          wxss += `  line-height: 1.6;\n`
          wxss += `}\n\n`
          break
      }
      
      return wxss
    },

    // 生成JS代码
    generateJS() {
      let js = `// index.js\n// 注意：如果您的项目使用了uniapp，可以考虑使用封装的request函数\n// 将wx.request替换为import request from '@/utils/request'然后使用request()\n\nPage({\n  data: {\n`
      
      // 添加数据
      js += `    campusName: '${this.getCampusName()}',\n`
      js += `    bannerList: [],\n`
      js += `    goodsList: [],\n`
      js += `    distributionGoodsList: [],\n`
      js += `    quickEntries: [],\n`
      js += `    entriesList: [],\n`
      js += `    noticeList: [],\n`
      js += `    recommendList: []\n`
      js += `  },\n\n`
      
      // 页面加载
      js += `  onLoad(options) {\n`
      js += `    this.loadPageData()\n`
      js += `  },\n\n`
      
      // 加载页面数据（推荐：使用统一接口）
      js += `  loadPageData() {\n`
      js += `    // 方式一：使用统一接口一次性获取所有数据（推荐）\n`
      js += `    wx.request({\n`
      js += `      url: 'http://localhost:5217/miniprogram/home-data',\n`
      js += `      method: 'GET',\n`
      js += `      success: (res) => {\n`
      js += `        if (res.statusCode === 200 && res.data.success) {\n`
      js += `          const data = res.data.data\n`
      js += `          // 处理图片URL，确保可以正常访问\n`
      js += `          const bannerList = (data.bannerList || []).map(item => {\n`
      js += `            return {\n`
      js += `              ...item,\n`
      js += `              image: item.image?.startsWith('http') ? item.image : 'http://localhost:5217' + item.image\n`
      js += `            }\n`
      js += `          })\n`
      js += `          \n`
      js += `          const goodsList = (data.goodsList || []).map(item => {\n`
      js += `            return {\n`
      js += `              ...item,\n`
      js += `              image: item.image?.startsWith('http') ? item.image : 'http://localhost:5217' + item.image\n`
      js += `            }\n`
      js += `          })\n`
      js += `          \n`
                js += `          const entriesList = (data.entriesList || []).map(item => {\n`
          js += `            return {\n`
          js += `              ...item,\n`
          js += `              builtInIcon: item.builtInIcon?.startsWith('http') ? item.builtInIcon : (item.builtInIcon ? 'http://localhost:5217' + item.builtInIcon : '')\n`
          js += `            }\n`
          js += `          })\n`
      js += `          \n`
      js += `          const recommendList = (data.recommendList || []).map(item => {\n`
      js += `            return {\n`
      js += `              ...item,\n`
                js += `              logo: item.logo?.startsWith('http') ? item.logo : 'http://localhost:5217' + item.logo\n`
      js += `            }\n`
      js += `          })\n`
      js += `          \n`
      js += `          const distributionGoodsList = (data.distributionGoodsList || []).map(item => {\n`
      js += `            return {\n`
      js += `              ...item,\n`
      js += `              goodPicture: item.goodPicture?.startsWith('http') ? item.goodPicture : 'http://localhost:5217' + item.goodPicture\n`
      js += `            }\n`
      js += `          })\n`
      js += `          \n`
      js += `          this.setData({\n`
      js += `            bannerList: bannerList,\n`
      js += `            goodsList: goodsList,\n`
      js += `            distributionGoodsList: distributionGoodsList,\n`
      js += `            quickEntries: data.quickEntries || [],\n`
      js += `            entriesList: entriesList,\n`
      js += `            noticeList: data.noticeList || [],\n`
      js += `            recommendList: recommendList\n`
      js += `          })\n`
      js += `        } else {\n`
      js += `          wx.showToast({\n`
      js += `            title: res.data.message || '数据加载失败',\n`
      js += `            icon: 'none'\n`
      js += `          })\n`
      js += `        }\n`
      js += `      },\n`
      js += `      fail: (err) => {\n`
      js += `        console.error('加载页面数据失败:', err)\n`
      js += `        wx.showToast({\n`
      js += `          title: '网络请求失败',\n`
      js += `          icon: 'none'\n`
      js += `        })\n`
      js += `        // 如果统一接口失败，可以fallback到分别调用\n`
      js += `        this.loadDataSeparately()\n`
      js += `      }\n`
      js += `    })\n`
      js += `  },\n\n`
      
      // 添加分别加载数据的备用方法
      js += `  loadDataSeparately() {\n`
      
      // 根据页面中的组件类型，只生成需要的数据加载代码
      const componentTypes = this.pageData.components.map(c => c.type)
      
      if (componentTypes.includes('banner')) {
        js += `    // 加载轮播图数据\n`
        js += `    this.loadBannerData()\n`
        js += `    \n`
      }
      
      if (componentTypes.includes('goods')) {
        js += `    // 加载商品数据\n`
        js += `    this.loadGoodsData()\n`
        js += `    \n`
      }

      if (componentTypes.includes('distribution-goods')) {
        js += `    // 加载分销商品数据\n`
        js += `    this.loadDistributionGoodsData()\n`
        js += `    \n`
      }
      
      if (componentTypes.includes('quick')) {
        js += `    // 加载快捷入口数据\n`
        js += `    this.loadQuickEntries()\n`
        js += `    \n`
      }
      
      if (componentTypes.includes('entries')) {
        js += `    // 加载功能入口数据\n`
        js += `    this.loadEntriesData()\n`
        js += `    \n`
      }
      
      if (componentTypes.includes('notice')) {
        js += `    // 加载校区公告数据\n`
        js += `    this.loadNoticeData()\n`
        js += `    \n`
      }
      
      if (componentTypes.includes('recommend')) {
        js += `    // 加载品牌推荐数据\n`
        js += `    this.loadRecommendData()\n`
        js += `    \n`
      }
      
      js += `  },\n\n`
      
      // 加载轮播图数据
      js += `  loadBannerData() {\n`
      js += `    // 调用API获取轮播图数据\n`
      js += `    wx.request({\n`
      js += `      url: 'http://localhost:5217/miniprogram/banners',\n`
      js += `      method: 'GET',\n`
      js += `      success: (res) => {\n`
      js += `        if (res.statusCode === 200 && res.data.success) {\n`
      js += `          const bannerList = (res.data.data.bannerList || []).map(item => {\n`
      js += `            return {\n`
      js += `              ...item,\n`
      js += `              image: item.image?.startsWith('http') ? item.image : 'http://localhost:5217' + item.image\n`
      js += `            }\n`
      js += `          })\n`
      js += `          this.setData({\n`
      js += `            bannerList: bannerList\n`
      js += `          })\n`
      js += `        }\n`
      js += `      },\n`
      js += `      fail: (err) => {\n`
      js += `        console.error('加载轮播图失败:', err)\n`
      js += `        wx.showToast({\n`
      js += `          title: '加载失败',\n`
      js += `          icon: 'none'\n`
      js += `        })\n`
      js += `      }\n`
      js += `    })\n`
      js += `  },\n\n`
      
      // 轮播图点击事件
      js += `  onBannerTap(e) {\n`
      js += `    const link = e.currentTarget.dataset.link\n`
      js += `    if (link) {\n`
      js += `      wx.navigateTo({ url: link })\n`
      js += `    }\n`
      js += `  },\n\n`
      
      // 商品点击事件
      js += `  onGoodsTap(e) {\n`
      js += `    const goodsId = e.currentTarget.dataset.id\n`
      js += `    wx.navigateTo({\n`
      js += `      url: '/pages/goods/detail?id=' + goodsId\n`
      js += `    })\n`
      js += `  },\n\n`

      // 分销商品点击事件
      js += `  onDistributionGoodsTap(e) {\n`
      js += `    const goodsId = e.currentTarget.dataset.id\n`
      js += `    wx.navigateTo({\n`
      js += `      url: '/pages/distribution-goods/detail?id=' + goodsId\n`
      js += `    })\n`
      js += `  },\n\n`
      
      // 快捷入口点击事件
      js += `  onQuickTap(e) {\n`
      js += `    const link = e.currentTarget.dataset.link\n`
      js += `    if (link) {\n`
      js += `      wx.navigateTo({ url: link })\n`
      js += `    }\n`
      js += `  },\n\n`

      // 添加其他组件的数据加载方法
      js += `  loadGoodsData() {\n`
      js += `    // 调用API获取商品数据\n`
      js += `    wx.request({\n`
      js += `      url: 'http://localhost:5217/miniprogram/goods',\n`
      js += `      method: 'GET',\n`
      js += `      success: (res) => {\n`
      js += `        if (res.statusCode === 200 && res.data.success) {\n`
      js += `          const goodsList = (res.data.data.goodsList || []).map(item => {\n`
      js += `            return {\n`
      js += `              ...item,\n`
      js += `              image: item.image?.startsWith('http') ? item.image : 'http://localhost:5217' + item.image\n`
      js += `            }\n`
      js += `          })\n`
      js += `          this.setData({\n`
      js += `            goodsList: goodsList\n`
      js += `          })\n`
      js += `        }\n`
      js += `      },\n`
      js += `      fail: (err) => {\n`
      js += `        console.error('加载商品失败:', err)\n`
      js += `        wx.showToast({\n`
      js += `          title: '加载商品失败',\n`
      js += `          icon: 'none'\n`
      js += `        })\n`
      js += `      }\n`
      js += `    })\n`
      js += `  },\n\n`

      js += `  loadDistributionGoodsData() {\n`
      js += `    // 调用API获取分销商品数据\n`
      js += `    wx.request({\n`
      js += `      url: 'http://localhost:5217/miniprogram/distribution-goods',\n`
      js += `      method: 'GET',\n`
      js += `      success: (res) => {\n`
      js += `        if (res.statusCode === 200 && res.data.success) {\n`
      js += `          const distributionGoodsList = (res.data.data.distributionGoodsList || []).map(item => {\n`
      js += `            return {\n`
      js += `              ...item,\n`
      js += `              goodPicture: item.goodPicture?.startsWith('http') ? item.goodPicture : 'http://localhost:5217' + item.goodPicture\n`
      js += `            }\n`
      js += `          })\n`
      js += `          this.setData({\n`
      js += `            distributionGoodsList: distributionGoodsList\n`
      js += `          })\n`
      js += `        }\n`
      js += `      },\n`
      js += `      fail: (err) => {\n`
      js += `        console.error('加载分销商品失败:', err)\n`
      js += `        wx.showToast({\n`
      js += `          title: '加载分销商品失败',\n`
      js += `          icon: 'none'\n`
      js += `        })\n`
      js += `      }\n`
      js += `    })\n`
      js += `  },\n\n`

      js += `  loadQuickEntries() {\n`
      js += `    // 调用API获取快捷入口数据\n`
      js += `    wx.request({\n`
      js += `      url: 'http://localhost:5217/miniprogram/quick-entries',\n`
      js += `      method: 'GET',\n`
      js += `      success: (res) => {\n`
      js += `        if (res.statusCode === 200 && res.data.success) {\n`
      js += `          this.setData({\n`
      js += `            quickEntries: res.data.data.quickEntries || []\n`
      js += `          })\n`
      js += `        }\n`
      js += `      },\n`
      js += `      fail: (err) => {\n`
      js += `        console.error('加载快捷入口失败:', err)\n`
      js += `        wx.showToast({\n`
      js += `          title: '加载快捷入口失败',\n`
      js += `          icon: 'none'\n`
      js += `        })\n`
      js += `      }\n`
      js += `    })\n`
      js += `  },\n\n`

      js += `  loadEntriesData() {\n`
      js += `    // 调用API获取功能入口数据\n`
      js += `    wx.request({\n`
      js += `      url: 'http://localhost:5217/miniprogram/entries',\n`
      js += `      method: 'GET',\n`
      js += `      success: (res) => {\n`
      js += `        if (res.statusCode === 200 && res.data.success) {\n`
                js += `          const entriesList = (res.data.data.entriesList || []).map(item => {\n`
          js += `            return {\n`
          js += `              ...item,\n`
          js += `              builtInIcon: item.builtInIcon?.startsWith('http') ? item.builtInIcon : (item.builtInIcon ? 'http://localhost:5217' + item.builtInIcon : '')\n`
          js += `            }\n`
          js += `          })\n`
      js += `          this.setData({\n`
      js += `            entriesList: entriesList\n`
      js += `          })\n`
      js += `        }\n`
      js += `      },\n`
      js += `      fail: (err) => {\n`
      js += `        console.error('加载功能入口失败:', err)\n`
      js += `        wx.showToast({\n`
      js += `          title: '加载功能入口失败',\n`
      js += `          icon: 'none'\n`
      js += `        })\n`
      js += `      }\n`
      js += `    })\n`
      js += `  },\n\n`

      js += `  loadNoticeData() {\n`
      js += `    // 调用API获取校区公告数据\n`
      js += `    wx.request({\n`
      js += `      url: 'http://localhost:5217/miniprogram/notices',\n`
      js += `      method: 'GET',\n`
      js += `      success: (res) => {\n`
      js += `        if (res.statusCode === 200 && res.data.success) {\n`
      js += `          this.setData({\n`
      js += `            noticeList: res.data.data.noticeList || []\n`
      js += `          })\n`
      js += `        }\n`
      js += `      },\n`
      js += `      fail: (err) => {\n`
      js += `        console.error('加载校区公告失败:', err)\n`
      js += `        wx.showToast({\n`
      js += `          title: '加载校区公告失败',\n`
      js += `          icon: 'none'\n`
      js += `        })\n`
      js += `      }\n`
      js += `    })\n`
      js += `  },\n\n`

      js += `  loadRecommendData() {\n`
      js += `    // 调用API获取品牌推荐数据\n`
      js += `    wx.request({\n`
      js += `      url: 'http://localhost:5217/miniprogram/recommends',\n`
      js += `      method: 'GET',\n`
      js += `      success: (res) => {\n`
      js += `        if (res.statusCode === 200 && res.data.success) {\n`
      js += `          const recommendList = (res.data.data.recommendList || []).map(item => {\n`
      js += `            return {\n`
      js += `              ...item,\n`
      js += `              logo: item.logo?.startsWith('http') ? item.logo : 'http://localhost:5217' + item.logo\n`
      js += `            }\n`
      js += `          })\n`
      js += `          this.setData({\n`
      js += `            recommendList: recommendList\n`
      js += `          })\n`
      js += `        }\n`
      js += `      },\n`
      js += `      fail: (err) => {\n`
      js += `        console.error('加载品牌推荐失败:', err)\n`
      js += `        wx.showToast({\n`
      js += `          title: '加载品牌推荐失败',\n`
      js += `          icon: 'none'\n`
      js += `        })\n`
      js += `      }\n`
      js += `    })\n`
      js += `  },\n\n`

      // 功能入口点击事件
      js += `  onEntryTap(e) {\n`
      js += `    const link = e.currentTarget.dataset.link\n`
      js += `    if (link) {\n`
      js += `      wx.navigateTo({ url: link })\n`
      js += `    }\n`
      js += `  },\n\n`

      // 校区公告点击事件
      js += `  onNoticeTap(e) {\n`
      js += `    const noticeId = e.currentTarget.dataset.id\n`
      js += `    wx.navigateTo({\n`
      js += `      url: '/pages/notice/detail?id=' + noticeId\n`
      js += `    })\n`
      js += `  },\n\n`

      // 品牌推荐点击事件
      js += `  onRecommendTap(e) {\n`
      js += `    const link = e.currentTarget.dataset.link\n`
      js += `    if (link) {\n`
      js += `      wx.navigateTo({ url: link })\n`
      js += `    }\n`
      js += `  },\n\n`

      // 图片点击事件
      js += `  onImageTap(e) {\n`
      js += `    const link = e.currentTarget.dataset.link\n`
      js += `    if (link) {\n`
      js += `      wx.navigateTo({ url: link })\n`
      js += `    }\n`
      js += `  },\n\n`

      // 添加页面生命周期
      js += `  onShow() {\n`
      js += `    // 页面显示时刷新数据\n`
      js += `    console.log('页面显示')\n`
      js += `  },\n\n`

      js += `  onHide() {\n`
      js += `    // 页面隐藏时的处理\n`
      js += `    console.log('页面隐藏')\n`
      js += `  },\n\n`

      js += `  onPullDownRefresh() {\n`
      js += `    // 下拉刷新\n`
      js += `    this.loadPageData()\n`
      js += `    wx.stopPullDownRefresh()\n`
      js += `  },\n\n`

      js += `  onReachBottom() {\n`
      js += `    // 上拉加载更多\n`
      js += `    console.log('触底加载更多')\n`
      js += `  },\n\n`

      // 如果有搜索组件，添加分享功能
      const hasSearch = this.pageData.components.some(c => c.type === 'search')
      if (hasSearch) {
        js += `  onShareAppMessage() {\n`
        js += `    return {\n`
        js += `      title: '${this.pageData.config.title || '艺术教育小程序'}',\n`
        js += `      path: '/pages/index/index'\n`
        js += `    }\n`
        js += `  },\n\n`

        js += `  onShareTimeline() {\n`
        js += `    return {\n`
        js += `      title: '${this.pageData.config.title || '艺术教育小程序'}'\n`
        js += `    }\n`
        js += `  }\n`
      } else {
        // 移除最后的逗号
        js = js.slice(0, -3) + '\n'
      }
      
      js += `})`
      
      this.jsCode = js
    },

    // 生成JSON配置
    generateJSON() {
      const config = {
        usingComponents: {},
        navigationBarTitleText: this.pageData.config.title || '艺术教育',
        navigationBarBackgroundColor: '#ffffff',
        navigationBarTextStyle: 'black',
        backgroundColor: this.pageData.config.backgroundColor || '#f5f5f5',
        enablePullDownRefresh: true,
        onReachBottomDistance: 50
      }

      // 检查是否有视频组件，添加视频相关配置
      const hasVideo = this.pageData.components.some(c => c.type === 'video')
      if (hasVideo) {
        config.requiredBackgroundModes = ['audio', 'location']
        config.enableCenterPlay = true
      }

      // 检查是否有轮播图组件，添加图片预览权限
      const hasBanner = this.pageData.components.some(c => c.type === 'banner')
      const hasImage = this.pageData.components.some(c => c.type === 'image')
      if (hasBanner || hasImage) {
        config.permission = {
          'scope.writePhotosAlbum': {
            desc: '保存图片到相册'
          }
        }
      }

      // 如果有搜索框，启用页面分享
      const hasSearch = this.pageData.components.some(c => c.type === 'search')
      if (hasSearch) {
        config.enableShareAppMessage = true
        config.enableShareTimeline = true
      }
      
      this.jsonCode = JSON.stringify(config, null, 2)
    },

    // 获取校区名称
    getCampusName() {
      const campusComponent = this.pageData.components.find(c => c.type === 'campus')
      return campusComponent?.data?.campusName || '默认校区'
    },

    // 复制代码
    copyCode(type) {
      let code = ''
      switch (type) {
        case 'wxml': code = this.wxmlCode; break
        case 'wxss': code = this.wxssCode; break
        case 'js': code = this.jsCode; break
        case 'json': code = this.jsonCode; break
      }
      
      navigator.clipboard.writeText(code).then(() => {
        this.$message.success('代码已复制到剪贴板')
      })
    },

    // 下载代码
    async downloadCode() {
      const zip = new JSZip()
      
      // 添加文件到zip
      zip.file('index.wxml', this.wxmlCode)
      zip.file('index.wxss', this.wxssCode)
      zip.file('index.js', this.jsCode)
      zip.file('index.json', this.jsonCode)
      
      // 生成并下载zip文件
      const content = await zip.generateAsync({ type: 'blob' })
      const url = URL.createObjectURL(content)
      const a = document.createElement('a')
      a.href = url
      a.download = 'miniprogram-page.zip'
      a.click()
      URL.revokeObjectURL(url)
      
      this.$message.success('代码包下载成功')
    },

    // 标签页切换
    handleTabClick(tab) {
      this.activeTab = tab.name
    }
  }
}
</script>

<style scoped>
.code-preview {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.preview-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #e0e0e0;
  background: #fafafa;
}

.preview-actions {
  padding: 0 20px;
}

.code-content {
  flex: 1;
  overflow: hidden;
}

.code-section {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.code-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 20px;
  background: #f8f9fa;
  border-bottom: 1px solid #e0e0e0;
}

.file-name {
  font-family: 'Courier New', monospace;
  font-size: 14px;
  color: #666;
}

pre {
  flex: 1;
  margin: 0;
  padding: 20px;
  background: #2d3748;
  color: #e2e8f0;
  font-family: 'Courier New', monospace;
  font-size: 13px;
  line-height: 1.5;
  overflow: auto;
}

code {
  white-space: pre-wrap;
  word-wrap: break-word;
}

/* 语法高亮样式 */
.language-xml .token.tag {
  color: #f7fafc;
}

.language-xml .token.attr-name {
  color: #90cdf4;
}

.language-xml .token.attr-value {
  color: #68d391;
}

.language-css .token.selector {
  color: #f6e05e;
}

.language-css .token.property {
  color: #90cdf4;
}

.language-css .token.punctuation {
  color: #e2e8f0;
}

.language-javascript .token.keyword {
  color: #f687b3;
}

.language-javascript .token.function {
  color: #90cdf4;
}

.language-javascript .token.string {
  color: #68d391;
}

.language-json .token.property {
  color: #90cdf4;
}

.language-json .token.string {
  color: #68d391;
}
</style> 